package com.fly.lambda.service;

import com.fly.lambda.dao.ConfigDAO;
import com.fly.lambda.domain.Config;
import com.fly.lambda.framework.dao.Pagination;
import com.fly.lambda.framework.utils.CommonUtils;
import com.fly.lambda.framework.web.cache.CacheManage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Fly on 2016/7/27.
 */
@Service
public class ConfigService {

    @Autowired
    ConfigDAO configDAO;
    @Autowired
    CacheManage cacheManage;

    /**
     * 初始化配置参数
     */
    @Transactional
    public void initConfig(){
        List<Config> configList = configDAO.getList();
        for(Config config: configList){
            cacheManage.setCache(config.getConfigName(), config.getConfigValue(), -1);
            System.out.println(cacheManage.get(config.getConfigName()).toString());
        }
    }

    /**
     * 通过Id获取Config
     * @param configId
     * @return
     */
    @Transactional
    public Config getConfigById(String configId){
        Config config = new Config();
        if (StringUtils.isNotBlank(configId)){
            config = configDAO.getById(configId);
        }
        return config;
    }

    /**
     * 保存配置参数
     * @param config
     */
    @Transactional
    public void saveConfig(Config config){
        if (StringUtils.isBlank(config.getConfigId())){
            config.setConfigId(CommonUtils.genPK());
            configDAO.create(config);
        }
        else{
            configDAO.update(config);
        }
    }

    /**
     * 根据Id删除参数
     * @param configId
     */
    @Transactional
    public void deleteConfigById(String configId){
        configDAO.deleteById(configId);
    }

    @Transactional
    public Pagination<Config> queryConfigPage(String queryStr, int curPage, int pageSize){
        return configDAO.queryConfigPage(queryStr, curPage, pageSize);
    }

}
